<?php
ini_set('opcache.revalidate_freq', 0);
if (!defined('__TYPECHO_ROOT_DIR__'))
    exit;
$today = getBingToday();
$url = $today['url'] ? $today['url'] : $today['urlstr'];
?>


<div class="time-bar">
    <!-- <div class="logoText">doubao.life</div> -->
    <div class="f1" id="datetime">&nbsp;</div>
    <div class="d-flex a-center link">
        <!-- <a href="javascript:;" class="-icon -qq"></a> -->
        <a href="https://www.pexels.com/zh-cn/@shean-john-2151965658/" target="_blank" class="pexelsLogo"></a>
        <a href="mailto:shean7577@icloud.com" class="-icon -mail -large"></a>
        <a href="javascript:;" onclick="goInfo()" class="-icon -search -large"></a>
    </div>
</div>
<div class="page-cover" style="background-image:url('<?php echo ($url); ?>');"></div>
<div class="loading-overlay">
    <div class="inner">
        <div class="text-center">
            <div class="-icon -loading -larget" style="margin:0 auto;"></div>
            <div class="loadingLogo">DOUBAO.LIFE</div>
        </div>
    </div>
</div>

<script>
    (() => {
        //when bkg loaded
        const overlay = document.querySelector('.loading-overlay')
        if (overlay) {
            let bkg = new Image();
            bkg.src = '<?php echo ($url); ?>'
            bkg.onload = () => {
                setTimeout(() => {
                    overlay.style.display = 'none'
                }, 500)
            }
        }

        //if local storage has background sets then use it
        loadStorageBkg()

        window.theme = getSystemTheme()
        document.body.setAttribute('data-theme', getSystemTheme());
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (event) => {
            const newTheme = event.matches ? 'dark' : 'light';
            document.body.setAttribute('data-theme', newTheme);
        });

        initAnimated()
        initWindow()
        initPostWindow()

        //接收子窗口里的消息事件
        window.addEventListener('message', function (event) {
            let fun = event.data
            if (fun.act === 'changeBkg') {
                saveStorageBkg(fun.val)
                let tar = document.querySelector('.page-cover')
                if (tar) {
                    tar.style.backgroundImage = "url('" + fun.val + "')"
                }
            }
            if (fun.act === 'setDefaultBkg') {
                let tar = document.querySelector('.page-cover')
                if (tar) {
                    tar.style.backgroundImage = "url('<?php echo ($url); ?>')"
                }
            }
            //post
            if (fun.act === 'viewPost' || fun.act === 'viewBing') {
                handlePostWindowOpen(fun.val)
            }
            //set title
            if (fun.act === 'setTitle') {
                let tarWindow = document.querySelector('.swindow .-title')
                //debugger
                if (tarWindow) {
                    tarWindow.innerHTML =
                        `<div class="-icon -small -search-colorful mr-1"></div><div>${fun.val}</div>`
                }
            }
        }, false);

        initDatetime()
    })({})

    function goInfo() {
        const menu_info = document.querySelector('.sideMenu-item[data-name="info"]')
        if (menu_info) menu_info.click()
    }

    function loadStorageBkg() {
        let cfg = localStorage.getItem('db_bkg')
        if (!cfg) return
        //background
        if (cfg) {
            let tar = document.querySelector('.page-cover')
            if (tar) {
                tar.style.backgroundImage = "url('" + cfg + "')"
            }
        }
    }

    function initDatetime() {
        let tar = document.querySelector('#datetime')
        if (!tar) {
            return
        }
        setInterval(() => {
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1; // getMonth()返回的是0-11，所以需要+1
            let day = now.getDate();
            let hours = now.getHours();
            let minutes = now.getMinutes();
            let seconds = now.getSeconds();

            // 确保月份和日期是两位数
            month = month < 10 ? '0' + month : month;
            day = day < 10 ? '0' + day : day;
            hours = hours < 10 ? '0' + hours : hours;
            minutes = minutes < 10 ? '0' + minutes : minutes;
            seconds = seconds < 10 ? '0' + seconds : seconds;
            let dateTimeString = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
            tar.innerHTML = dateTimeString;
        }, 500);
    }

    function saveStorageBkg(val) {
        localStorage.setItem('db_bkg', val)
    }

    function getSystemTheme() {
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            return 'dark';
        } else {
            return 'light';
        }
    }

    function initAnimated() {
        const ifr = document.querySelector('iframe')
        ifr.onload = () => {

        }
        ifr.onerror = () => {

        }

        //菜单栏菜单项
        let eles = document.querySelectorAll('.sideMenu>.sideMenu-item')
        for (let i = 0; i < eles.length; i++) {
            eles[i].addEventListener('mouseover', () => {
                if (eles[i].classList.contains('active')) {
                    eles[i].classList.add('animate__headShake')
                } else {
                    eles[i].classList.add('animate__jello')
                }
            })
            eles[i].addEventListener('mouseleave', () => {
                eles[i].classList.remove('animate__headShake')
                eles[i].classList.remove('animate__jello')
            })
            //点击菜单项
            eles[i].addEventListener('click', () => {
                let sw = document.querySelector('.swindow')
                if (sw) {
                    sw.classList.replace('animate__zoomOutRight', 'animate__bounceInRight')
                }
                removeMenuActive(eles, eles[i])
                handleWindowOpen(eles[i])
            })
        }
        //swindow关闭按钮
        let closeBtn = document.querySelector('.swindow>.sw-header>.-close>.-icon')
        if (closeBtn) {
            closeBtn.addEventListener('mouseover', () => {
                closeBtn.classList.add('animate__jello')
            })
            closeBtn.addEventListener('mouseleave', () => {
                closeBtn.classList.remove('animate__jello')
            })
            //点击sw关闭按钮
            closeBtn.addEventListener('click', () => {
                let sw = document.querySelector('.swindow')
                if (sw) sw.classList.add('animate__zoomOutRight')
                removeMenuActive(eles, null)
            })
        }
        //默认打开关于网站窗口info
        const menu_info = document.querySelector('.sideMenu-item[data-name="info"]')
        if (menu_info) menu_info.click()

        function removeMenuActive(eles, addle = null) {
            for (let i = 0; i < eles.length; i++) {
                if (eles[i].classList.contains('active')) {
                    eles[i].classList.remove('active')
                }
            }
            if (addle) {
                addle.classList.add('active')
            }
        }

        function handleWindowOpen(menu) {
            const name = menu.dataset.name
            const label = menu.dataset.label
            const type = menu.dataset.type
            const win = document.querySelector('.swindow')
            const win_title = win.querySelector('.-title')
            const size = menu.dataset.size
            if (win_title) win_title.innerHTML = `
            <div class="-icon -small -${name} mr-1"></div><div>${label}</div>
        `

            const ifr = document.querySelector('iframe')
            if (ifr) {
                if (type === 'page') {
                    ifr.src = '/index.php/' + name + '<?php echo '.html'; ?>'
                }
                if (type === 'category') {
                    ifr.src = '/index.php/category/' + name + '/'
                }
            }
            if (win) {
                if (size === 'large') {
                    win.classList.remove('small')
                    win.classList.add('large')
                } else {
                    win.classList.add('small')
                    win.classList.remove('large')
                }
            }
        }
    }

    function initPostWindow() {
        let closeBtn = document.querySelector('.postWindow>.postWindow-header>.-close>.-icon')
        if (closeBtn) {
            closeBtn.addEventListener('mouseover', () => {
                closeBtn.classList.add('animate__jello')
            })
            closeBtn.addEventListener('mouseleave', () => {
                closeBtn.classList.remove('animate__jello')
            })
            //点击sw关闭按钮
            closeBtn.addEventListener('click', () => {
                let pw = document.querySelector('#post')
                if (!pw) return
                pw.classList.remove('animate__backInRight')
                pw.classList.add('animate__backOutRight')
            })
        }
    }

    function handlePostWindowOpen(val) {
        let pw = document.querySelector('#post')
        let ifr = pw.querySelector('iframe')
        let title = pw.querySelector('.-title .titleHere')
        if (!pw || !ifr) return
        pw.style.display = 'block'
        pw.classList.remove('animate__backOutRight')
        pw.classList.add('animate__backInRight')
        ifr.src = val.url
        if (title) {
            title.innerHTML = val.title
        }
        ifr.onload = () => {
            console.log(ifr)
        }
    }

    function initWindow() {
        const draggable = document.getElementById('draggable');

        let isDragging = false;
        let offsetX, offsetY;

        function constrainToBounds(element) {
            const rect = element.getBoundingClientRect();
            const maxLeft = window.innerWidth - rect.width;
            const maxTop = window.innerHeight - rect.height;

            if (rect.left < 0) {
                element.style.left = '0px';
            } else if (rect.right > maxLeft) {
                element.style.left = `${maxLeft}px`;
            }

            if (rect.top < 0) {
                element.style.top = '0px';
            } else if (rect.bottom > maxTop) {
                element.style.top = `${maxTop}px`;
            }
        }
        draggable.addEventListener('mouseenter', () => {
            document.body.style.cursor = 'grab';
        })
        draggable.addEventListener('mouseleave', () => {
            document.body.style.cursor = 'default';
        })
        draggable.addEventListener('mousedown', (e) => {
            isDragging = true;
            offsetX = e.clientX - draggable.offsetLeft;
            offsetY = e.clientY - draggable.offsetTop;
            document.body.style.cursor = 'grabbing';
        });

        document.addEventListener('mouseup', () => {
            isDragging = false;
            document.body.style.cursor = 'default';
        });

        document.addEventListener('mousemove', (e) => {
            if (isDragging) {
                draggable.style.left =
                    `${Math.min(Math.max(e.clientX - offsetX, 0), window.innerWidth - draggable.offsetWidth)}px`;
                draggable.style.top =
                    `${Math.min(Math.max(e.clientY - offsetY, 0), window.innerHeight - draggable.offsetHeight)}px`;
            }
        });
    }
</script>